package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceimpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    //新增权限
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    //分页
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);

        Page<Permission> page =  permissionDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //id查询权限
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    //编辑权限
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    //删除权限
    public void delete(Integer id) {
        long count = permissionDao.selectCountByPermissionId(id);
        if(count > 0){
            throw new RuntimeException(MessageConstant.DELETE_PERMISSION_FAIL);
        }else {
            permissionDao.delete(id);
        }
    }

    //查询所有
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    //根据角色id查询关联的权限id
    public List<Integer> findPermissionIdsByRoleId(Integer roleId) {
        return permissionDao.findPermissionIdsByRoleId(roleId);
    }

}
